package com.yzkj.framework.core.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.utils.IOUtils;
import com.yzkj.framework.beans.exception.YzkjException;
import com.yzkj.framework.core.config.TencentCOSProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;

@Slf4j
@Component
public class TencentCOSHelper {

    @Autowired
    TencentCOSProperties tencentCOSProperties;

    private COSClient createCosClient() {
        // 创建COS 凭证
        COSCredentials credentials = new BasicCOSCredentials(tencentCOSProperties.getSecretId(), tencentCOSProperties.getSecretKey());

        // 配置 COS 区域 就购买时选择的区域
        ClientConfig clientConfig = new ClientConfig(new Region(tencentCOSProperties.getRegion()));

        // 创建 COS 客户端连接

        return new COSClient(credentials, clientConfig);
    }

    public String readFile(String key) {

        COSClient cosClient = this.createCosClient();

        GetObjectRequest getObjectRequest = new GetObjectRequest(tencentCOSProperties.getBucketName(), key);
        COSObjectInputStream cosObjectInput;

        try {
            COSObject cosObject = cosClient.getObject(getObjectRequest);
            cosObjectInput = cosObject.getObjectContent();
        } catch (CosClientException e) {
            log.error("cos错误", e);
            throw YzkjException.of("cos异常");
        }

        // 处理下载到的流
        // 这里是直接读取，按实际情况来处理
        byte[] bytes = null;
        if (cosObjectInput == null) {
            log.error("文件流为空");
            throw YzkjException.of("文件流为空");
        }
        try {
            bytes = IOUtils.toByteArray(cosObjectInput);
            String filePath = "./tempFile_" + UUID.fastUUID().toString();

            FileUtil.writeBytes(bytes, filePath);

        } catch (IOException e) {
            log.error("读取文件失败");
            throw YzkjException.of("文件流为空");
        } finally {
            // 用完流之后一定要调用 close()
            try {
                cosObjectInput.close();
            } catch (IOException e) {
                log.error("cos错误", e);
            }
        }

        // 在流没有处理完之前，不能关闭 cosClient
        // 确认本进程不再使用 cosClient 实例之后，关闭之
        cosClient.shutdown();

        return null;
    }

    public String uploadFile(String moduleName, File file) {

        COSClient cosClient = this.createCosClient();
        String fileName = file.getName();
        try {
            File localFile;
            localFile = file;
            String key = moduleName + "/" + RandomUtils.createSimpleUUID() + "/" + fileName;
            // 将 文件上传至 COS
            PutObjectRequest objectRequest = new PutObjectRequest(tencentCOSProperties.getBucketName(), key, localFile);
            cosClient.putObject(objectRequest);

            Date expiration = new Date(new Date().getTime() + 15 * 60 * 1000);
            URL downloadUrl = cosClient.generatePresignedUrl(tencentCOSProperties.getBucketName(), key, expiration);
            return "http://" + downloadUrl.getHost() + downloadUrl.getPath();
        } catch (Exception e) {
            log.error("上传cos失败 moduleName => {}", moduleName, e);
        } finally {
            cosClient.shutdown();
        }

        return null;
    }

    public String uploadFile(String moduleName, MultipartFile file) {

        // 创建COS 凭证
        COSCredentials credentials = new BasicCOSCredentials(tencentCOSProperties.getSecretId(), tencentCOSProperties.getSecretKey());

        // 配置 COS 区域 就购买时选择的区域
        ClientConfig clientConfig = new ClientConfig(new Region(tencentCOSProperties.getRegion()));

        // 创建 COS 客户端连接
        COSClient cosClient = new COSClient(credentials, clientConfig);
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            throw YzkjException.of("文件名为空");
        }
        try {
            String substring = fileName.substring(fileName.lastIndexOf("."));
            File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), substring);
            file.transferTo(localFile);
            String key = moduleName + "/" + RandomUtils.createSimpleUUID() + "/" + fileName;
            // 将 文件上传至 COS
            PutObjectRequest objectRequest = new PutObjectRequest(tencentCOSProperties.getBucketName(), key, localFile);
            cosClient.putObject(objectRequest);

            Date expiration = new Date(new Date().getTime() + 15 * 60 * 1000);
            URL downloadUrl = cosClient.generatePresignedUrl(tencentCOSProperties.getBucketName(), key, expiration);
            return "http://" + downloadUrl.getHost() + downloadUrl.getPath();
        } catch (Exception e) {
            log.error("上传cos失败 moduleName => {}", moduleName, e);
        } finally {
            cosClient.shutdown();
        }

        return null;
    }
}
